package com.zhanghe.study.net.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP服务端
 */
public class TcpServer {
    public static void main(String[] args) {


        try(
                // 创建一个ServerSocket对象
                ServerSocket serverSocket = new ServerSocket(9090);
                // accept方法，返回Socket对象
                Socket s = serverSocket.accept();
                // 获取输入流
                InputStream is = s.getInputStream();
                // 输出流，给客户端返回消息
                OutputStream os = s.getOutputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader reader = new BufferedReader(isr);
        ){
            String str;
            while ((str = reader.readLine()) != null){
                System.out.print(str);
            }
            os.write("我已收到消息".getBytes());
            System.out.println("------------");
            System.out.println("收到来自"+s.getInetAddress().getHostAddress()+"的消息");
        } catch (IOException e){
            e.printStackTrace();
        }

    }
}
